/*
 * @Description:常用工具方法
 * @Author: wangfuwei
 * @Date: 2020-11-30 18:31:23
 * @LastEditors: wangfuwei
 * @LastEditTime: 2020-12-06 22:56:27
 * @FilePath: /horizon-frontend/src/utils/util.js
 */
/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent("HTMLEvents");
  event.initEvent("resize", true, true);
  event.eventType = "message";
  window.dispatchEvent(event);
}

/**
 * 是否IE浏览器
 */
export function isIE() {
  const bw = window.navigator.userAgent;
  const compare = s => bw.indexOf(s) >= 0;
  const ie11 = (() => "ActiveXObject" in window)();
  return compare("MSIE") || ie11;
}

/**
 * 16进制颜色转换为RGB颜色
 */
export function colorToRgb(color) {
  const reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
  /* 16进制颜色转为RGB格式 */
  var sColor = color.toLowerCase();
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
      }
      sColor = sColorNew;
    }
    // 处理六位的颜色值
    var sColorChange = [];
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
    }
    return sColorChange.join(",");
  } else {
    return sColor;
  }
}

/**
 * RGB颜色转16进制颜色
 */
export function rgbToHex(r, g, b) {
  r = parseInt(r);
  g = parseInt(g);
  b = parseInt(b);
  let hex = ((r << 16) | (g << 8) | b).toString(16);

  const length = hex.length;
  for (let i = 0; i < 6 - length; i++) {
    hex = "0" + hex;
  }
  return "#" + hex;
}

/**
 * 动态注入Style
 * @param {*} id
 * @param {*} style
 */
export function appendStyle(id, style) {
  var node = document.getElementById(id);
  if (node) node.parentNode.removeChild(node);

  node = document.createElement("style");
  node.type = "text/css";
  node.id = id;

  if (node.styleSheet) node.styleSheet.cssText = style;
  else node.innerHTML = style;
  document.getElementsByTagName("head")[0].appendChild(node);
}

/**
 * 根据节点Tag获取最近的父节点
 */
export function getParentByTag(node, tag) {
  if (node && node.tag && node.tag.toLowerCase().indexOf(tag.toLowerCase()) !== -1) {
    return node;
  }

  if (node.parent) {
    return getParentByTag(node.parent);
  }

  return null;
}
